package top.tan.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import top.tan.entity.Visitor;
import top.tan.pojo.vo.IpQueryResultVO;
import top.tan.repository.VisitorRepository;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class VisitorServiceImpl implements VisitorService {

    private static final Logger logger = LoggerFactory.getLogger(VisitorServiceImpl.class);

    @Autowired
    private VisitorRepository repository;

    private static final String IP_QUERY_URL = "https://tool.lu/ip/ajax.html";

    @Override
    public Visitor save(HttpServletRequest request) {
        String ip = getIpAddr(request);
        Visitor visitor = repository.findByIp(ip);
        if (visitor == null) {
            visitor = new Visitor();
            visitor.setIp(ip);
            visitor.setTimes(1);
            visitor.setCreateTime(new Date());
            // 获取淘宝提供的ip归属地
            String tb_location = ipDetailQuery(ip).getText().getTb_location();
            visitor.setLocation(tb_location);
        } else {
            visitor.setTimes(visitor.getTimes() + 1);
            visitor.setUpdateTime(new Date());
        }
        repository.save(visitor);

        return visitor;
    }

    private static IpQueryResultVO ipDetailQuery(String ip) {
        // 设置请求实体
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("ip", ip);
        // 使用restTemplate请求接口,POST请求, 传参必须使用MultiValueMap，详细参考：https://www.cnblogs.com/shoren/p/RestTemplate-problem.html
        RestTemplate restTemplate = new RestTemplate();
        IpQueryResultVO result = restTemplate.postForObject(IP_QUERY_URL, paramMap, IpQueryResultVO.class);
        logger.info(result.toString());

        return result;
    }

    /*
     * 测试 ipDetailQuery 方法
     */
//    public static void main(String[] args) {
//        IpQueryResultVO ipQueryResultVO = ipDetailQuery("62.168.46.226");
//        System.out.println(ipQueryResultVO);
//    }

    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
}
